package com.yy.util.http;

import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * Created by Administrator on 2015/4/20.
 */
public class IOHelper {

    public static String toString(InputStream stream, String charsetName) {
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = null;
        if (charsetName.equals("") || TextUtils.isEmpty(charsetName)) {
            charsetName = "utf-8";
        }
        try {
            reader = new BufferedReader(new InputStreamReader(stream, charsetName));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String line = "";
        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static InputStream toStream(String text, String charsetName) {
        ByteArrayInputStream bis = null;
        if (charsetName.equals("") || TextUtils.isEmpty(charsetName)) {
            charsetName = "utf-8";
        }
        try {
            bis = new ByteArrayInputStream(text.getBytes(charsetName));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return bis;
    }
}
